﻿using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace SMF.HowTo.Shared.Commands
{
    public static class Click
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
            "Command",
            typeof (ICommand),
            typeof (Click),
            new PropertyMetadata(new PropertyChangedCallback(OnCommandPropertyChanged))
            );

        public static void SetCommand(ButtonBase element, ICommand value)
        {
            element.SetValue(CommandProperty, value);
        }

        public static ICommand GetCommand(ButtonBase element)
        {
            return (ICommand) element.GetValue(CommandProperty);
        }

        private static void OnCommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var button = d as ButtonBase;

            if (button != null)
            {
                button.Click += HandleButtonClick;
            }
        }

        private static void HandleButtonClick(object sender, RoutedEventArgs e)
        {
            var button = sender as ButtonBase;

            if (button != null)
            {
                ICommand command = GetCommand(button);

                //TODO: Not currently supporting command argument
                if (command != null && command.CanExecute(null))
                {
                    command.Execute(null);
                }
            }
        }
    }
}